package com.brower.sun;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends Activity {

    private WebView webView;
    private ProgressBar progressBar;
    private Handler handler = new Handler();
    private String imei;
    private String[] permissions = {Manifest.permission.READ_PHONE_STATE,Manifest.permission.READ_CONTACTS
            ,Manifest.permission.CALL_PHONE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        Log.e("TAG", MobileInfoUtil.getIMEI(this) + "????");
//        Log.e("TAG", stringToAscii(MobileInfoUtil.getIMEI(this)) + "????");
        Log.e("TAG", getUniqueId(this) + "????");

        progressBar = (ProgressBar) findViewById(R.id.progressbar);//进度条
        imageView = (ImageView) findViewById(R.id.iv_bg);
//        imei = MobileInfoUtil.getIMEI(this);
        imei = DeviceIdUtils.getLocalDeviceId(this);
        final HttpUtils httpUtils = new HttpUtils();
        final BitmapUtils bitmapUtils = new BitmapUtils(this);
        if(!TextUtils.isEmpty(SharedPreferencesUtils.getString(MainActivity.this,"image",""))){
            bitmapUtils.display(imageView, SharedPreferencesUtils.getString(MainActivity.this,"image",""));
        }
        webView = (WebView) findViewById(R.id.webview);
        PermissionsUtil.requestPermission(this, new PermissionListener() {
            @Override
            public void permissionGranted(String[] permission) {
//                MyUtils.showToast(MainActivity.this,"已同意");
//                imei = MobileInfoUtil.getIMEI(MainActivity.this);
                imei = DeviceIdUtils.getLocalDeviceId(MainActivity.this);
                httpUtils.send(HttpRequest.HttpMethod.GET, "http://m.guito.cn/face?IMEI=" + imei, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        Log.e("TAG", responseInfo.result+"????"+MobileInfoUtil.getValueByName(responseInfo.result,"TT"));
//                        String url=Environment.getExternalStorageDirectory() + "/Android/data/com.brower.sun/mainbg.jpg";
//                        File file=new File(url);
//                        if(file.exists()){
//                            file.delete();
//                        }
                        httpUtils.download(responseInfo.result, Environment.getExternalStorageDirectory() + "/Android/data/com.brower.sun/"+System.currentTimeMillis()+".jpg", new RequestCallBack<File>() {
                            @Override
                            public void onSuccess(ResponseInfo<File> responseInfo) {
                                Log.e("TAG",responseInfo.result.getAbsolutePath());
                                SharedPreferencesUtils.setString(MainActivity.this,"image",responseInfo.result.getAbsolutePath());
                            }

                            @Override
                            public void onFailure(HttpException error, String msg) {
                                Log.e("TAG",msg);
                            }
                        });
                        initwebview(MobileInfoUtil.getValueByName(responseInfo.result,"TT"));
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Log.e("TAG", s);
                    }
                });
            }

            @Override
            public void permissionDenied( String[] permission) {
//                .showToast(MainActivity.this, "已拒绝，程序可能无法使用");
                Toast.makeText(MainActivity.this,"已拒绝，程序可能无法使用",Toast.LENGTH_SHORT);
            }
        }, permissions, true, new PermissionsUtil.TipInfo("授权", "为了保证程序的正常运行，请授予我权限！", "不同意", "同意"));
//        webView.loadUrl("file:///android_asset/test.html");//加载asset文件夹下html

    }

    private void initwebview(String yz) {
        if(TextUtils.isEmpty(imei)){
            imei=getUniqueId(this);
        }
        webView.loadUrl("http://m.guito.cn?IMEI=" + imei + "&YZ=" +yz + "&P=");//加载url
//        webView.loadUrl("http://m.guito.cn/1.html");//加载url
        //使用webview显示html代码
//        webView.loadDataWithBaseURL(null,"<html><head><title> 欢迎您 </title></head>" +
//                "<body><h2>使用webview显示 html代码</h2></body></html>", "text/html" , "utf-8", null);
        webView.addJavascriptInterface(this, "android");//添加js监听 这样html就能调用客户端
        webView.setWebChromeClient(webChromeClient);
        webView.setWebViewClient(webViewClient);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//允许使用js
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        webView.setVisibility(View.VISIBLE);
                    }
                });
            }
        }, 3000);
        /**
         * LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
         * LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
         * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //支持屏幕缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDefaultTextEncodingName("GBK");

        //不显示webview缩放按钮
        webSettings.setDisplayZoomControls(false);
    }

    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            progressBar.setVisibility(View.GONE);
            imageView.setVisibility(View.GONE);
            webView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("ansen", "拦截url:" + url.toLowerCase());
            if (url.equals("http://www.google.com/")) {
                Toast.makeText(MainActivity.this, "国内不能访问google,拦截该url", Toast.LENGTH_LONG).show();
                return true;//表示我已经处理过了
            }
            if(url.toLowerCase().contains("cmd=restart")){
                Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                startActivity(intent);
                return true;
            }

            return super.shouldOverrideUrlLoading(view, url);
        }

    };

    private AlertDialog.Builder builder;
    private AlertDialog alertDialog;
    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, final JsResult result) {

            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            Log.e("TAG",url+message);
            builder = new AlertDialog.Builder(MainActivity.this);
            alertDialog = builder.setTitle("提示信息:")
                    .setMessage(message)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            result.confirm();
                        }
                    }).create();
            alertDialog.show();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.i("ansen", "网页标题:" + title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("ansen", "是否有上一个页面:" + webView.canGoBack());
        if (webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            webView.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * JS调用android的方法
     *
     * @param str
     * @return
     */
    @JavascriptInterface //仍然必不可少
    public void getClient(String str) {
        Log.i("ansen", "html调用客户端:" + str);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //释放资源
        webView.destroy();
        webView = null;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 字符串转换为Ascii
     *
     * @param value
     * @return
     */
    public int stringToAscii(String value) {
        int number = 0;
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]).append(",");
            } else {
                sbu.append((int) chars[i]);
            }
            number += (int) chars[i];
        }
        Log.e("TAG", sbu.toString());
        return number;

    }


    public int getUserDate() {
        int number = 0;
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String dateString = formatter.format(currentTime);
        Log.e("TAG", dateString);
        String[] datas = dateString.split("-");
        for (String data : datas) {
            number += Integer.valueOf(data);
        }
        return number;
    }
    public  String getUniqueId(Context context){
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        return id;
//        try {
//            return toMD5(id);
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//            return id;
//        }
    }
}
